import { observable, action } from "mobx";
import data from "../../../apis/data";
import table from "../../../apis/table";
import app from "../../../apis/app";

const PAGE_SIZE = 10;
const state = {
  table: {
    loading: false,
    columns: [],
    datas: []
  },
  pagination: null
};

export default class AppDataStore {
  @observable dataKey = null;
  @observable table = state.table;
  @observable pagination = state.pagination;
  @observable noForm = false;
  @observable isInit = false;

  @action init = appid => {
    this.isInit = false;

    data.getDataKey(appid).then(data => {
      return data && data.datas;
    }).then(dataKey => {
      this.isInit = true;

      if (!dataKey) {
        this.noForm = true;
        return;
      }
      this.dataKey = dataKey;
      this.getDatas();
      this.getCounts();
    });
  }

  @action getDatas = (current = 1) => {
    this.table.loading = true;

    app.getDatas(this.dataKey, current).then(({ columns, datas }) => {
      const keys = columns.map(c => c.dataIndex);
      const table = { loading: false };

      table.columns = columns.map(c => {
        const n = {
          hide: c.hide,
          title: c.title,
          key: c.dataIndex,
          dataIndex: c.dataIndex,
        };

        if (c.dataIndex === 'creator') {
          n.width = 140;
        }

        return n;
      });

      table.datas = datas.map((data, i) => {
        let o = { key: String(i), checked: false };

        keys.forEach(key => {
          o[key] = data[`${key}span`];
        });

        return o;
      });

      this.table = table;
    });
  }

  @action initState = () => {
    this.dataKey = null;
    this.noForm = false;
    this.table = state.table;
    this.pagination = state.pagination;
  }

  getCounts() {
    table.getCounts(this.dataKey).then(({ count }) => {
      const pagination = {
        current: 1,
        total: Math.ceil(count / PAGE_SIZE),
        onChange: this.onCurrentChange.bind(this)
      };

      if (this.pagination) {
        pagination.current = this.pagination.current;
      }

      this.pagination = pagination;
    });
  }

  onCurrentChange(current) {
    this.pagination.current = current;
    this.getDatas(current);
    this.getCounts();
  }
}